#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/12/6 9:47
# @Author  : Beam
# @Site    : 
# @File    : saltcollect.py
# @Software: PyCharm

from config import setting
import json
import requests

#处理InsecureRequestWarning错误
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

class SaltApi(object):
	def __init__(self):
		self.url = setting.APIURL
		self.username = setting.USERNAME
		self.password = setting.PASSWORD
		self.headers = {
			"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
			"Content-type": "application/json"
		}
		self.params = {'client': 'local', 'fun': '', 'tgt': ''}
		self.login_url = self.url + "login"
		self.login_params = {'username': self.username, 'password': self.password, 'eauth': 'pam'}
		self.token = self.get_data(self.login_url, self.login_params)['token']  #第一次请求
		self.headers['X-Auth-Token'] = self.token

	def get_data(self, url, params):
		'''带参数提交到api接口'''
		send_data = json.dumps(params)
		request = requests.post(url, data=send_data, headers=self.headers, verify=False).json()
		# response = request.json()
		result = dict(request)
		return result['return'][0]

	def getresult(self,client, commad, arg=None):
		"""远程执行命令，相当于salt 'client1' cmd.run 'free -m'"""
		if arg:
			params = {'client': 'local', 'fun': commad, 'tgt': client, 'arg': arg}
		else:
			params = {'client': 'local', 'fun': commad, 'tgt': client}
		result = self.get_data(self.url, params)
		return result

	def getfoo(self):

		return True


